import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators'; // 导入 map 操作符
import { LogService } from 'src/log/log.service';
import { OperationLog } from 'src/log/entities/log.entity';
import { Reflector } from '@nestjs/core';
import { Request } from 'express'; // 导入 Express 的 Request 类型

export interface Response<T> {
  data: T;
}

@Injectable()
export class OperationLogInterceptor<T>
  implements NestInterceptor<T, Response<T>>
{
  constructor(
    private readonly logService: LogService,
    private readonly reflector: Reflector, // 注意这里修正了拼写错误 reflactor -> reflector
  ) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest<Request>();
    const title = this.reflector.get<string>( // 同样修正拼写错误
      'logOperationTitle',
      context.getHandler(),
    );

    // 使用 map 操作符确保返回正确的 Response<T> 类型
    return next.handle().pipe(
      tap(() => {
        const log = new OperationLog();
        log.title = title;
        log.method = request.method;
        log.url = request.url;
        log.ip = request.ip || '';
        log.params = JSON.stringify({
          ...request.query,
          ...request.params,
          ...request.body,
        });
        log.user_agent = request.headers['user-agent'] || '';
        if (request.user && typeof request.user['username'] === 'string') {
          log.username = request.user['username'];
        }
        this.logService.saveOperationLog(log).catch((err) => {
          console.log(err);
        });
      }),
    );
  }
}
